const _ = require('lodash')


class Wrapper {
    constructor(name, fn) {
        this.name = name
        this.fn = fn
        this.logger = require('../singleton').logger.child({label: name})
    }

    process(item, {request, response, spider, stop}) {
        const logger = this.logger
        const result = this.fn(item, {request, response, spider, logger, stop})
        return _.defaultTo(result, item)
    }
}


class Pipeline {
    constructor(configuration) {
        this.processors = []
    }

    pipe(name, fn) {
        this.processors.push(new Wrapper(name, fn))
    }

    process(item, {request, response, spider}) {
        let inputItem = item;
        let stopped = false
        for(let processor of this.processors) {
            inputItem = processor.process(inputItem, {
                request, response, spider,
                stop() {
                    stopped = true
                },
            })
            if (stopped) {
                break
            }
        }
    }
}

module.exports = (configuration) => {
    return new Pipeline(configuration)
}
